<template>
  <view class="verify-box" :class="gglass" @click="onclick">
    <c-text :color="colors">{{
      second ? second + " S" : $t("mine.setting.accounts.getCode")
    }}</c-text>
  </view>
</template>

<script setup lang="ts">
import {
  defineProps,
  reactive,
  toRefs,
  computed,
  onMounted,
  getCurrentInstance,
} from "vue";
import { phoneVerify } from "../ways/verify";
const { proxy } = getCurrentInstance() as any;

const props = defineProps({
  gglass: {
    type: String,
    default: "",
  },
  sec: {
    type: [Number, String],
    default: 60,
  },
  phone: {
    type: [Number, String],
    default: "",
  },
  color: {
    type: String,
    default: "",
  },
  api: {
    type: String,
    default: "VerificationCodeApi/VerificationCode",
  },
  range_key: {
    type: String,
    default: "mobile",
  },
  type: {
    //0-绑定手机号，1-登录，2-修改密码，3-忘记密码，4-注册
    type: Number,
    default: 0,
  },
});
const state = reactive<{
  interval: number | undefined;
  second: number;
}>({
  interval: undefined,
  second: 0,
});
const { interval, second } = toRefs(state);

const colors = computed(() => {
  return proxy.$color[props.color] || props.color;
});

const onclick = () => {
  if (state.second) return;
  if (!phoneVerify(props.phone.toString(), proxy.$t("mine.setting.accounts.errorPhon")))
    return;
  state.second = props.sec as number;
  clearInterval(state.interval);
  state.interval = setInterval(() => {
    state.second--;
    if (state.second <= 0) {
      clearInterval(state.interval);
      state.second = 0;
    }
  }, 1000);
  proxy.$http.post(
    `${props.api}?${props.range_key}=${props.phone}&type=${props.type}`
  );
};
</script>

<style lang="scss" scoped>
.verify-box {
  display: inline-block;
  font-size: 28rpx;
  white-space: nowrap;
}
</style>
